<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\MemberNews as M;
use app\common\util\Upload as Up;
use think\captcha\facade\Captcha;
use think\facade\Request;
use app\common\service\AdminAdmin as S;

class Api extends Base
{

    public function index(){
        return json_encode(Request::root());
    }

    public function userenroll(){
        //用户注册
        $data = Request::post();
        if(empty($data['phone'])){
            return $this->getJson();
        }
        $data['re_time'] = date('Y-m-d H:i:s');
        $id = M::create($data);
        if($id){
            return $this->getJson(M::where('phone', $data['phone'])->find());
        }
        return $this->getJson();
    }
    public function userlogin(){
        //用户登录
        $data = Request::post();
        if(empty($data['phone'])){
            return $this->getJson();
        }
        $user = M::where('phone', $data['phone'])->find();
        if($user){
            $data['login_time'] = date('Y-m-d H:i:s');
            $data['id'] = $user['id'];
            M::update($data);
            return $this->getJson($user);
        }else{
            return $this->getJson();
        }
    }
    //保存订单
    public function saveorder(){
        //用户等级
        $data = Request::post();
        if(empty($data['name'])){
            return $this->getJson();
        }
        $data['staus'] = '资料审核中';
        $data['orderid'] =  $data['apk'].date('YmdHis').time();
        if(!$data['img']){
            return  $this->getJson();
        }
        //签名
        $data['img'] = $this->img($data['img']);
        $is =\app\common\model\OrderNews::create($data);
        if($is){
            return $this->getJson( $this->savesta($data));
        }
        return $this->getJson();
    }
    //查看订单
    public function getorder(){
        $data = Request::post();
        if(empty($data['phone'])){
            return $this->getJson();
        }
        $order = \app\common\model\OrderNews::where('phone', $data['phone'])->find();
        if($order){
            return $this->getJson($order);
        }
        return $this->getJson();
    }
    //上传
    function  upload(){
        if(empty(Request::file()) || Request::post('path')){
            return $this->getJson();
        }
        return $this->getJson(Up::putFile(Request::file(),Request::post('path')));
    }
    //查询会员等级
    public function getmemberconfig(){
        //用户等级
        return $this->getJson( \app\common\model\MemberconfigIndex::select());
    }
    //查询订单提示
    public function getorderconfig(){
        return $this->getJson( \app\common\model\OdersconfigIndex::select());
    }
    //支付
    public function pay(){
        $data = Request::post();
        if(empty($data['amount']) || empty($data['name'])  || empty($data['email'])  || empty($data['phone']) ){
            return $this->getJson();
        }
        $jsapi_params = $saveData =  [
            'merchantLogin' => 'zzJ0aUs0VlmLqONGO2BS',
            'orderCode' => 'code'.$data['apk'].$data['phone'].time(),
            'amount' =>$data['amount'],
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'remark' => $data['remark']
        ];
        $jsapi_params['sign'] =$this->makeSignature($jsapi_params,'pXToB5JOcRR3adB67JNd');
//        $jsapi_params['sign'] =$this->generateSign($jsapi_params,'pXToB5JOcRR3adB67JNd');
        $url = 'https://hxpayment.net/payment/collection';
        $post = $this->curl_post_https($url, json_encode($jsapi_params));
        if(is_array($post)){
            $post = json_decode($post);
            $saveData['apk'] =  $data['apk'];
            //添加
            \app\common\model\MemberPayindex::create($saveData);
        }
        $this->getJson( $post);
    }

    function savesta($data){
        $oredrSum =$this->getOrderTimeSum($data['apk']);
        $datas=[
            'apk'=>$data['apk'],
            'enroll'=>$this->getUserTimeSum($data['apk'],'re_time'),
            'login'=>$this->getUserTimeSum($data['apk'],'login_time'),
            'zl1'=>$oredrSum,
            'zl2'=>$oredrSum,
            'zl3'=>$oredrSum,
            'v1'=>$this->getUserTimeSum($data['apk'],'','v1'),
            'v2'=>$this->getUserTimeSum($data['apk'],'','v2'),
            'v3'=>$this->getUserTimeSum($data['apk'],'','v3'),
            'v4'=>$this->getUserTimeSum($data['apk'],'','v4'),
            'v5'=>$this->getUserTimeSum($data['apk'],'','v5'),
            'amount'=>$this->getOrderTimeSum($data['apk'],'price')
        ];
        return \app\common\service\StatisticsIndex::goAdd($datas);
    }

    function  img($clearBase64){
        $pregInfo = preg_match('/^(data:\s*image\/(\w+);base64,)/', $clearBase64, $photoInfo);
        if (!in_array($photoInfo[2], array('jpg', 'png', 'bmp'))) {
            throw new Exception('图像格式错误');
        }
        if (!$pregInfo) {
            throw new Exception('图像格式错误');
        }
        $clearBase64HeadWithPhoto = str_replace($photoInfo[1], '', $clearBase64);
        $clearBase64HeadWithPhoto = str_replace(' ', '+', $clearBase64HeadWithPhoto);
        $imagePath = BaseModel::saveImg($clearBase64HeadWithPhoto, $photoInfo[2]);
        if (!$imagePath) {
            throw new Exception('上传失败');
        }
        return $imagePath;
    }
    function saveImg($base64Img,$ext){
        $documentRoot = ROOT_PATH . 'public';
        $relativePath = '/uploads/' . date("Ymd", time());
        $fullPath = $documentRoot . $relativePath;
        if (!is_dir($fullPath)) {       //判断目录是否存在 不存在就创建 并赋予777权限
            mkdir($fullPath, 0777, true);
        }
        $md5 = md5($base64Img);
        $rand = $md5 . rand(111, 999) . '.' . $ext;
        $relativePath .= '/' . $md5 . $rand;
        $imagePath = $fullPath . '/' . $md5 . $rand;
        try {
            file_put_contents($imagePath, base64_decode($base64Img));
            return $relativePath;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    function getUserTimeSum($apk,$key,$where){
       $sql =  M::where('apk','=',$apk);
       if($where){
           $sql=$sql->where('grade','=',$where);
       }
       if(!$key){
           $key ='create_time';
       }
       $sql->where($key,'<',date("Y-m-d H:i:s") )
            ->where($key,'>',date("Y-m-d").' 00:00:00' )
            ->count();
    }
    function getOrderTimeSum($apk,$sum){
        $sql =\app\common\model\OrderNews::where('apk','=',$apk)
            ->where('create_time','<',date("Y-m-d H:i:s") )
            ->where('create_time','>',date("Y-m-d").' 00:00:00' );
        if($sum){
            return $sql->sum($sum);
        }else{
            return $sql->count();
        }
    }

    //签名算法
    function makeSignature($args,$key)
    {
//        ksort($args);
//        $str = urldecode();
//        return md5(http_build_query($args) . "&key=" . $key);
//        ksort($args);
        $stringA = '';
        foreach($args as $k => $v) {
            $stringA .= $k . '=' . $v . '&';
        }
        $stringSignTemp =  $stringA.'key='.$key;
        return md5($stringSignTemp);
    }
    public function getJson($da=[]){
        if(empty($da)){
            return json_encode(['msg'=>'操作失败,参数不全','code'=>201]);
        }else{
            return json_encode(['msg'=>'成功','code'=>200,'data'=>$da]);
        }
    }
    /* PHP CURL HTTPS POST */
    function curl_post_https($url, $data)
    { // 模拟提交数据函数
        $header = array(
            'Content-Type:' . 'application/json; charset=UTF-8',
            'Accept:application/json',
        );
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
}
